<?php
namespace app\admin\model;

use think\Db;
use think\Model;
class BaseModel extends Model
{
    protected $where = [];
    protected $count_field = 'id';
    protected $table_name = '';
    protected $prefix = 'rg_';
    protected $resultSetType = 'collection';
    public function __construct($data = [])
    {
        $this->table = $this->prefix.$this->table_name;
        parent::__construct($data);
    }

    public function getStatusAttr($data){
        return $data == 1 ? '启用':'禁用';
    }


    // 原生sql查询
    public function querySql($sql=''){
        if($sql){
            $list = Db::query($sql);
            return !empty($list) ? $list : [];
        }

    }

    // 原生sql执行
    public function execSql($sql=''){
        if($sql){
            $bool = Db::execute($sql);
            return $bool;
        }
    }


    // 單表保存（新增）
    public function addData($data){
        $insert_id = Db::table($this->table)->insertGetId($data);
        return $insert_id > 0 ? $insert_id : false;
    }

    // 更新
    public function updateData($where,$data){
        if($where){
            $bool = Db::table($this->table)->where($where)->update($data);
            return $bool;
        }
    }

    // 單表單條查詢
    public function findData($where,$field='*',$order='id desc'){
        $data = Db::table($this->table)->field($field)->order($order)->where($where)->find();
        return !empty($data) ? $data : [];
    }

    // 單表多條查詢
    public function selectData($where,$field='*',$order='id desc'){
        $data = Db::table($this->table)->field($field)->order($order)->where($where)->select();
        return !empty($data) ? $data : [];
    }

    // 获取最大版本version的主键id
    public function maxId($where){
        $data = Db::table($this->table)->field('id')->order('version desc')->where($where)->find();
        return !empty($data) ? $data['id'] : 0;
    }


    // 統計自增長
    public function setCount(){

    }



    //物理删除
    public function deleteTrue($where=[]){
        if(!empty($where)){
            $bool = Db::table($this->table)->where($where)->delete();
            return $bool;
        }
    }

    //逻辑删除
    public function deleteFalse($where=[]){
        if(!empty($where)){
            $data['is_delete']   = 1;
            $bool = Db::table($this->table)->where($where)->update($data);
            return $bool;
        }
    }

    // 输出sql
    public function getSql(){
        return Db::table($this->table)->getLastSql();
    }
}
